import os
import re

from flask import Flask, request, jsonify, Response, send_file
from .config import Config
from .services import *
from .services.pinxiang_services import PinxiangServices
from .services.user_services import UserService
from .services.platform_view_services import PlatformViewServices
from .services.logSearchPriceExe_services import LogSearchPriceExeServices
from .services.customer_information_services import CustomerInformationService
from .utils import clean_NaN_in_listDict, check_xlsx, get_random_xlsx_name, sortByMaybeNumStr, tran_to_intArray, \
    is_valid_datetime, int_formatter, thousandth_round_formatter, precentage_round_formatter, float_round_formatter, \
    datetime_formatter

from datetime import timedelta
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity, exceptions


def create_app():
    _app = Flask(__name__)
    _app.config['UPLOAD_FOLDER'] = Config.UPLOAD_FOLDER
    return _app


app = create_app()
app.config['JWT_SECRET_KEY'] = Config.SECRET_KEY
app.config['JWT_ERROR_MESSAGE_KEY'] = None
jwt = JWTManager(app)


@app.errorhandler(exceptions.JWTExtendedException)
def handle_jwt_error(error):
    response = jsonify({
        'code': 401,
        'msg': 'Unauthorized',
    })
    response.status_code = 401  # 设置 HTTP 响应码为 401 Unauthorized
    return response


@jwt.unauthorized_loader
def unauthorized_callback(callback):
    return {
        'code': 401,
        'msg': 'Unauthorized',
    }, 401


expires = timedelta(hours=5)


@app.route('/getCompetingGmvData', methods=['POST'])
@jwt_required()
def getTmallGmvStatlist():
    try:
        unit = request.form.get("unit")
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = get_competing_gmv_data(startDate, endDate, unit, "天猫")
        sortBy = request.form.get("sortBy")
        asc = request.form.get("asc")
        asc = True if asc else False
        if sortBy in ["数据统计时间", "竞店店铺名称", "排名", "累计GMV", "GMV同比增长", "累计GMV同比增长"]:
            res = res.sort_values(by=sortBy, ascending=asc)
        res = precentage_round_formatter(res, ["GMV同比增长", "累计GMV同比增长", "GMV环比增长"])
        res = float_round_formatter(res,
                                    ["上一年同期GMV", "上一年同期累计GMV", "竞店GMV（卫生巾&私处护理市场）", "累计GMV",
                                     "前一周GMV"])
        res = int_formatter(res, ["排名", "数据记录数量"])
        res = datetime_formatter(res, ["数据统计时间"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/getCompetingGmvDataDouyin', methods=['POST'])
@jwt_required()
def getTmallGmvDataDouyin():
    try:
        unit = request.form.get("unit")
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = get_competing_gmv_data(startDate, endDate, unit, "抖音")
        sortBy = request.form.get("sortBy")
        asc = request.form.get("asc")
        asc = True if asc else False
        if sortBy in ["数据统计时间", "竞店店铺名称", "排名", "累计GMV", "GMV同比增长", "累计GMV同比增长"]:
            res = res.sort_values(by=sortBy, ascending=asc)
        res = precentage_round_formatter(res, ["GMV同比增长", "累计GMV同比增长", "GMV环比增长"])
        res = float_round_formatter(res,
                                    ["上一年同期GMV", "上一年同期累计GMV", "竞店GMV（卫生巾&私处护理市场）", "累计GMV",
                                     "前一周GMV"])
        res = int_formatter(res, ["排名", "数据记录数量"])
        res = datetime_formatter(res, ["数据统计时间"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/getOnlineComplement', methods=['POST'])
@jwt_required()
def getOnlineComplement():
    try:
        brandName = request.form.get("brandName")
        statTime = request.form.get("statTime")
        filterBrand = request.form.get("filterBrand")
        aggregate = request.form.get("aggregate")
        res = get_online_complement(brandName, statTime, filterBrand, aggregate)
        res = int_formatter(res, ["月度排名", "累计排名"])
        res = datetime_formatter(res, ["数据统计时间"])
        res = float_round_formatter(res, ["本月实际", "本月差异", "本月计划", "累计实际", "累计差异", "累计计划"])
        res = precentage_round_formatter(res, ["本月完成率", "累计完成率"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/pinxiangExe', methods=['POST'])
@jwt_required()
def pinxiangExe():
    try:
        start_date = request.form.get("beginDate")
        if not isinstance(start_date, str) or is_valid_datetime(start_date) is False:
            return {'code': 400, 'msg': '开始时间格式有误'}
        end_date = request.form.get("endDate")
        if not isinstance(end_date, str) or is_valid_datetime(end_date) is False:
            return {'code': 400, "msg": "结束时间格式有误"}
        target_store_name = request.form.get("targetStoreName")
        if not isinstance(target_store_name, str):
            target_store_name = ""
        res = pinxiang_exe(start_date, end_date, target_store_name)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None or res.empty:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/pinxiangExport', methods=['POST'])
@jwt_required()
def pinxiangExport():
    try:
        start_date = request.form.get("beginDate")
        if not isinstance(start_date, str) or is_valid_datetime(start_date) is False:
            return {'code': 400, 'msg': '开始时间格式有误'}
        end_date = request.form.get("endDate")
        if not isinstance(end_date, str) or is_valid_datetime(end_date) is False:
            return {'code': 400, "msg": "结束时间格式有误"}
        target_store_name = request.form.get("targetStoreName")
        if not isinstance(target_store_name, str):
            target_store_name = ""
        data = PinxiangServices.exportXlsx(start_date, end_date, target_store_name)

        # 发送文件作为响应
        res = send_file(path_or_file=data,
                        download_name=f"from{start_date}to{end_date}.xlsx",
                        as_attachment=True)
        return res
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/getTmallFlagshipStoreOverview', methods=['POST'])
@jwt_required()
def getTamllOverviewlist():
    try:
        unit = request.form.get("unit")
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = get_tmall_flagship_store_overview(startDate, endDate, unit)
        res = int_formatter(res, ["加购人数", "支付买家数", "支付新买家数", "支付老买家数", "收藏人数", "新增会员人数",
                                  "访客数"])
        res = float_round_formatter(res, ["GMV", "UV", "会员成交金额", "刷单金额", "实际实收", "客单价", "推广GMV",
                                          "推广费用", "新客GMV", "日销GMV", "日销推广GMV和", "淘客GMV", "淘客费用",
                                          "直播佣金", "直播坑位费", "老客GMV", "自播GMV", "达播GMV", "退款金额"])
        res = datetime_formatter(res, ["数据生成时间", "数据统计时间"])
        res = precentage_round_formatter(res, ["支付转化率", "直播佣金比例"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/getTmallPromotionData', methods=['POST'])
@jwt_required()
def getTmallFourPromotionsMergeStatlist():
    try:
        unit = request.form.get("unit")
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        promotionChannel = request.form.get("promotionChannel")
        if promotionChannel == None:
            promotionChannel = ""
        res = get_tmall_promotion_data(startDate, endDate, unit, promotionChannel)
        sortBy = request.form.get("sortBy")
        asc = request.form.get("asc")
        asc = True if asc else False
        if sortBy in ["数据统计时间", "推广渠道"]:
            res = res.sort_values(by=sortBy, ascending=asc)
        res = int_formatter(res, ["展现量","总成交笔数","总购物车数","收藏宝贝数","收藏店铺数","点击量"])
        res = float_round_formatter(res, ["平均点击花费","总成交金额","花费"])
        res = precentage_round_formatter(res, ["投资回报率","点击率","点击转化率"])
        res = datetime_formatter(res, ["数据统计时间"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/getTmallPromotionSumData', methods=['POST'])
@jwt_required()
def getTmallFourPromotionsSumlist():
    try:
        unit = request.form.get("unit")
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = get_tmall_promotion_sum_data(startDate, endDate, unit)
        res = int_formatter(res, ["展现量","总成交笔数","点击量"])
        res = float_round_formatter(res, ["CPC","UV价值","总成交金额","花费"])
        res = precentage_round_formatter(res, ["投资回报率","转化率"])
        res = datetime_formatter(res, ["数据统计时间"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/dyFlagshipStoreLivingRoomDayStatExe', methods=['POST'])
@jwt_required()
def dyFlagshipStoreLivingRoomDayStatExe():
    try:
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        targetLiver = request.form.get("targetLiver")
        if targetLiver == None or not isinstance(targetLiver, str):
            targetLiver = ""
        res = dy_flagship_store_living_room_day_stat_exe(startDate, endDate, targetLiver)
        sortBy = request.form.get("sortBy")
        asc = request.form.get("asc")
        asc = True if asc else False
        if sortBy in ["数据统计时间", "达人"]:
            res = res.sort_values(by=sortBy, ascending=asc)
        res = int_formatter(res, ["直播时长", "直播次数", "直播间最高在线人数", "直播间平均在线人数"])
        res = thousandth_round_formatter(res, ["直播间商品观看-成交率(次数)"])
        res = precentage_round_formatter(res, ["直播折扣率", "直播赠品费率", "直播总费率"])
        res = float_round_formatter(res,
                                    ["直播间成交金额", "直播间退款金额", "直播实收", "直播开单销售额", "直播服务费",
                                     "直播佣金", "直播roi"])
        res = datetime_formatter(res, ["数据统计时间"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None or res.empty:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/dtkCompetingBrandPromotionDayStatExe', methods=['POST'])
@jwt_required()
def dtkCompetingBrandPromotionDayStatExe():
    try:
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = dtk_competing_brand_promotion_day_stat_exe(startDate, endDate)
        sortBy = request.form.get("sortBy")
        asc = request.form.get("asc")
        asc = True if asc else False
        if sortBy in ["数据统计时间", "竞品品牌名"]:
            res = res.sort_values(by=sortBy, ascending=asc)
        res = float_round_formatter(res, ["优惠券金额", "商品券后价", "佣金比例"])
        res = int_formatter(res, ["当日热销"])
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = res.to_dict("records")
    return {'code': 200, 'data': res}


@app.route('/checkPriceExe', methods=['POST'])
@jwt_required()
def checkPriceExe():
    try:
        current_user_id = get_jwt_identity()
        current_user_id = current_user_id if isinstance(current_user_id, int) else int(current_user_id)
        flag, msg, user = UserService.get_user_by_id(current_user_id)
        if not flag:
            return {'code': 400, 'msg': msg}
        good_actual_price = float(request.form.get("goodActualPrice"))
        product_bar_code_and_product_num = request.form.get("productBarCodeAndProductNum")
        res = check_price_exe(good_actual_price, product_bar_code_and_product_num)
        if res is None:
            res = []
            LogSearchPriceExeServices.addLogSearchPriceExe(user, None, datetime.now(), good_actual_price,
                                                           product_bar_code_and_product_num)
        else:
            res[0] = int_formatter(res[0], ["包数", "单包片数", "总片数"])
            res[0] = float_round_formatter(res[0],
                                           ["单包大促底价", "单包开单", "单包日促底价", "单包赠品成本", "单包零售价",
                                            "总大促底价", "总开单", "总日促底价", "总赠品成本", "总零售价"])
            res[1] = int_formatter(res[1], ["总包数合计", "总片数合计"])
            res[1] = float_round_formatter(res[1], ["到手价", "总大促底价合计", "总开单合计", "总日促底价合计",
                                                    "总赠品成本合计", "片单价"])
            res[1] = precentage_round_formatter(res[1], ["折扣费率", "赠品占比"])
            res = [res[0].to_dict("records"), res[1].to_dict("records")]
            if isinstance(res[1], list) and len(res[1]) > 0:
                LogSearchPriceExeServices.addLogSearchPriceExe(user, res[1][0], datetime.now(), good_actual_price,
                                                               product_bar_code_and_product_num)
            else:
                LogSearchPriceExeServices.addLogSearchPriceExe(user, None, datetime.now(), good_actual_price,
                                                               product_bar_code_and_product_num)
        return {'code': 200, 'data': res}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/uploadTmallFlagshipStoreOverviewDayInput', methods=['POST'])
@jwt_required()
def uploadTmallFlagshipStoreOverviewDayInput():
    file = request.files['file']
    if not (file and check_xlsx(file.filename)):
        return {'code': 400, 'msg': "未获取到xlsx文件"}
    random_file_name = get_random_xlsx_name()
    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name)
        file.save(file_path)
        upload_df = pd.read_excel(file_path)  # 前端修改
        # 上传入库
        info = upload_nostattime_insert(upload_df, table_zh_name='天猫旗舰店概况日表输入表',
                                        class_name=tmall_flagship_store_overview_day_input)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    return {'code': 200, 'msg': info}


@app.route('/putTmallFlagshipStoreOverviewDayInput', methods=['POST'])
@jwt_required()
def putTmallFlagshipStoreOverviewDayInput():
    classObject = tmall_flagship_store_overview_day_input(
        upload_time=datetime.now(),
        create_time=datetime.now(),
        stat_time=request.form.get("statTime"),
        living_commission_rate=request.form.get("livingCommissionRate"),
        living_slot_cost=request.form.get("livingSlotCost"),
        fake_order_amount=request.form.get("fakeOrderAmount")
    )
    try:
        info = nostattime_insert(classObject)
        return {'code': 200, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/getTmallFlagshipStoreOverviewDayInput', methods=['POST'])
@jwt_required()
def getTmallFlagshipStoreOverviewDayInput():
    try:
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = display_uploaded_ondate(tmall_flagship_store_overview_day_input, '天猫旗舰店概况日表输入表', startDate,
                                      endDate)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/uploadDyFlagshipStoreLivingRoomDay', methods=['POST'])
@jwt_required()
def uploadDyFlagshipStoreLivingRoomDay():
    file = request.files['file']
    if not (file and check_xlsx(file.filename)):
        return {'code': 400, 'msg': "未获取到xlsx文件"}
    random_file_name = get_random_xlsx_name()
    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name)
        file.save(file_path)
        upload_df = pd.read_excel(file_path)  # 前端修改
        # 上传入库
        info = upload_nostattime_insert(upload_df, table_zh_name='抖音旗舰店直播间日表',
                                        class_name=dy_flagship_store_living_room_day)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    return {'code': 200, 'msg': info}


@app.route('/getDyFlagshipStoreLivingRoomDay', methods=['POST'])
@jwt_required()
def getDyFlagshipStoreLivingRoomDay():
    try:
        startDate = request.form.get("beginDate")
        endDate = request.form.get("endDate")
        res = display_uploaded_ondate(dy_flagship_store_living_room_day, '抖音旗舰店直播间日表', startDate, endDate)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        sortBy = request.form.get("sortBy")
        asc = request.form.get("asc")
        asc = True if asc else False
        if sortBy in ["数据统计时间"]:
            res = res.sort_values(by=sortBy, ascending=asc)
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/uploadTmallFlagCompetingStoreList', methods=['POST'])
@jwt_required()
def uploadTmallFlagCompetingStoreList():
    file = request.files['file']
    if not (file and check_xlsx(file.filename)):
        return {'code': 400, 'msg': "未获取到xlsx文件"}
    random_file_name = get_random_xlsx_name()
    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name)
        file.save(file_path)
        upload_df = pd.read_excel(file_path)  # 前端修改
        # 上传入库
        info = upload_allupdate_insert(upload_df=upload_df, table_zh_name='天猫旗舰店竞店列表表',
                                       class_name=tmall_flag_competing_store_list)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    return {'code': 200, 'msg': info}


@app.route('/getTmallFlagCompetingStoreList', methods=['POST'])
@jwt_required()
def getTmallFlagCompetingStoreList():
    try:
        res = display_uploaded(tmall_flag_competing_store_list, '天猫旗舰店竞店列表表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/uploadCompetingBrandList', methods=['POST'])
@jwt_required()
def uploadCompetingBrandList():
    file = request.files['file']
    if not (file and check_xlsx(file.filename)):
        return {'code': 400, 'msg': "未获取到xlsx文件"}
    random_file_name = get_random_xlsx_name()
    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name)
        file.save(file_path)
        upload_df = pd.read_excel(file_path)  # 前端修改
        # 上传入库
        info = upload_allupdate_insert(upload_df=upload_df, table_zh_name='竞品列表表', class_name=competing_brand_list)
        # 读取展示上传数据
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    return {'code': 200, 'msg': info}


@app.route('/getCompetingBrandList', methods=['POST'])
@jwt_required()
def getCompetingBrandList():
    try:
        res = display_uploaded(competing_brand_list, '竞品列表表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/uploadProductDetails', methods=['POST'])
@jwt_required()
def uploadProductDetails():
    file1 = request.files['productDetailsFile']
    if not (file1 and check_xlsx(file1.filename)):
        return {'code': 400, 'msg': "productDetailsFile:未获取到xlsx文件"}
    random_file_name1 = get_random_xlsx_name()

    file2 = request.files['brandFile']
    if not (file2 and check_xlsx(file2.filename)):
        return {'code': 400, 'msg': "brandFile:未获取到xlsx文件"}
    random_file_name2 = get_random_xlsx_name()

    try:
        file_path1 = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name1)
        file1.save(file_path1)
        file_path2 = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name2)
        file2.save(file_path2)

        # 前端传入表（excel）:产品明细上传表、价格体系上传表
        upload_df_product_details = pd.read_excel(file_path1, sheet_name=None)
        upload_df_price_system_jietingsheet = pd.read_excel(file_path2, sheet_name='洁婷', header=2)
        upload_df_price_system_paiyangzhuangsheet = pd.read_excel(file_path2, sheet_name='派样装',
                                                                  header=6)
        info = good_product_related_upload_process(upload_df_product_details, upload_df_price_system_jietingsheet,
                                                   upload_df_price_system_paiyangzhuangsheet)
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    return {'code': 200, 'msg': info}


@app.route('/getGoodProductCombination', methods=['POST'])
@jwt_required()
def getGoodProductCombination():
    try:
        res = display_uploaded(good_product_combination, '产品组合表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getGoodProductCode', methods=['POST'])
@jwt_required()
def getGoodProductCode():
    try:
        res = display_uploaded(good_product_code, '产品代码表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getGoodProductPrice', methods=['POST'])
@jwt_required()
def getGoodProductPrice():
    try:
        res = display_uploaded(good_product_price, '产品价格表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getGoodGiveawayItemPrice', methods=['POST'])
@jwt_required()
def getGoodGiveawayItemPrice():
    try:
        res = display_uploaded(good_giveaway_item_price, '赠品价格表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getGoodIndicator', methods=['POST'])
@jwt_required()
def getGoodIndicators():
    try:
        res = display_uploaded(good_indicator, '商品指标表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/uploadPlanMonth', methods=['POST'])
@jwt_required()
def uploadPlanMonth():
    file = request.files['file']
    if not (file and check_xlsx(file.filename)):
        return {'code': 400, 'msg': "未获取到xlsx文件"}
    random_file_name = get_random_xlsx_name()
    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], random_file_name)
        file.save(file_path)
        upload_df = pd.read_excel(file_path, sheet_name=None, header=0)  # 前端修改
        # 上传入库
        pinxiang_jihua_upload(df=upload_df)
        # 读取展示上传数据
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    return {'code': 200, 'msg': "success"}


@app.route('/getPlanMonth', methods=['POST'])
@jwt_required()
def getPlanMonth():
    try:
        res = display_uploaded(plan_month, '计划月表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getDeliverSaleBagMonth', methods=['POST'])
@jwt_required()
def getDeliverSaleBagMonth():
    try:
        res = display_uploaded(deliver_sale_bag_month, '发货销售拆包月表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getDeliverSaleMonth', methods=['POST'])
@jwt_required()
def getDeliverSaleMonth():
    try:
        res = display_uploaded(deliver_sale_month, '发货销售月表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getProductInformation', methods=['POST'])
@jwt_required()
def getProductInformation():
    try:
        res = display_uploaded(product_information, '产品信息表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getCustomerInformation', methods=['POST'])
@jwt_required()
def getCustomerInformation():
    try:
        res = display_uploaded(customer_information, '客户信息表')
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
    if res is None:
        res = []
    else:
        res = clean_NaN_in_listDict(res.to_dict("records"))
    return {'code': 200, 'data': res}


@app.route('/getLogSearchPrice', methods=['POST'])
@jwt_required()
def getGetSearchPrice():
    query = {}
    start_time = request.form.get('startTime')
    end_time = request.form.get('endTime')
    searchUser_name = request.form.get('searchUserName')
    page_index = request.form.get('pageIndex')
    page_size = request.form.get('pageSize')
    if isinstance(start_time, str) and len(start_time) > 0:
        query['startTime'] = start_time
    if isinstance(end_time, str) and len(end_time) > 0:
        query['endTime'] = end_time
    if isinstance(searchUser_name, str) and len(searchUser_name) > 0:
        query['searchUserName'] = searchUser_name
    if isinstance(page_index, int) or (isinstance(page_index, str) and len(page_index) > 0):
        query['pageIndex'] = page_index
    if isinstance(page_size, int) or (isinstance(page_size, str) and len(page_size) > 0):
        query['pageSize'] = page_size
    try:
        flag, info = LogSearchPriceExeServices.getLogSearchPriceExes(query)
        if flag == False:
            return {'code': 400, 'msg': info}
        return {'code': 200, 'data': [result.tran_to_dict() for result in info]}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/login', methods=['POST'])
def loginUser():
    username = request.form.get('username')
    password = request.form.get('password')
    uflag, viewsOrMsg, user = UserService.check_login(username, password)
    if not uflag:
        return {'code': 400, 'msg': viewsOrMsg}
    access_token = create_access_token(identity=str(user.id), fresh=True, expires_delta=expires)
    if user.role_type == -1:
        vflag, views = PlatformViewServices.get_platform_views()
        if not vflag:
            return {'code': 400, 'msg': views}
        if views is None or len(views) == 0:
            return {'code': 200, 'data': {'views': [], 'user': user.tran_to_dict(), 'access_token': access_token}}
        return {'code': 200, 'data': {'views': [result.tran_to_dict() for result in views], 'user': user.tran_to_dict(),
                                      'access_token': access_token}}
    viewIds = tran_to_intArray(user.views)
    if viewIds is None or len(viewIds) == 0:
        return {'code': 200, 'data': {'views': [], 'user': user.tran_to_dict(), 'access_token': access_token}}
    vflag, views = PlatformViewServices.get_platform_view_by_ids(viewIds)
    if not vflag or len(views) == 0:
        return {'code': 200, 'data': {'views': [], 'user': user.tran_to_dict(), 'access_token': access_token}}
    return {'code': 200, 'data': {'views': [result.tran_to_dict() for result in views], 'user': user.tran_to_dict(),
                                  'access_token': access_token}}


@app.route('/loginByToken', methods=['POST'])
@jwt_required()
def loginByToken():
    current_user_id = get_jwt_identity()
    current_user_id = current_user_id if isinstance(current_user_id, int) else int(current_user_id)
    flag, msg, user = UserService.get_user_by_id(current_user_id)
    if not flag:
        return {'code': 400, 'msg': msg}
    if user.role_type == -1:
        vflag, views = PlatformViewServices.get_platform_views()
        if not vflag:
            return {'code': 400, 'msg': views}
        if views is None or len(views) == 0:
            return {'code': 200, 'data': {'views': [], 'user': user.tran_to_dict()}}
        return {'code': 200,
                'data': {'views': [result.tran_to_dict() for result in views], 'user': user.tran_to_dict()}}
    viewIds = tran_to_intArray(user.views)
    vflag, views = PlatformViewServices.get_platform_view_by_ids(viewIds)
    if not vflag or len(views) == 0:
        return {'code': 200, 'data': {'views': [], 'user': user.tran_to_dict()}}
    return {'code': 200, 'data': {'views': [result.tran_to_dict() for result in views], 'user': user.tran_to_dict()}}


@app.route('/register', methods=['POST'])
@jwt_required()
def registerUser():
    username = request.form.get('userName')
    password = request.form.get('password')
    roleType = request.form.get('roleType')
    personname = request.form.get('personName')
    views = request.form.get('views')
    if not username or not password or len(password) > 16:
        return {'code': 400, 'msg': "请正确输入用户名与密码"}
    try:
        roleType = int(roleType)
    except Exception as e:
        roleType = 0
    flag, info = UserService.register_user(username, password, roleType, personname, views)
    if not flag:
        return {'code': 400, 'msg': info}
    return {'code': 200, 'data': info}


@app.route('/unregister', methods=['POST'])
@jwt_required()
def deleteUserInfo():
    try:
        userId = request.form.get('id')
        userId = userId if isinstance(userId, int) else int(userId)
        if not userId or not isinstance(userId, int):
            return {'code': 400, 'msg': '参数异常:userId'}
        flag, info = UserService.delete_user(userId)
        if not flag:
            return {'code': 400, 'msg': info}
        return {'code': 200, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/getAllUserInfo', methods=['POST'])
@jwt_required()
def getAllUserInfo():
    try:
        flag, info = UserService.get_all_users()
        if flag:
            data = [result.tran_to_dict() for result in info]
            return {'code': 200, 'data': data}
        else:
            return {'code': 400, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/searchUsers', methods=['POST'])
@jwt_required()
def search_users():
    try:
        user_name = request.form.get('userName')
        person_name = request.form.get('personName')
        flag, info = UserService.search_users(user_name, person_name)
        if flag:
            data = [result.tran_to_dict() for result in info]
            return {'code': 200, 'data': data}
        else:
            return {'code': 400, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/editUser', methods=['POST'])
@jwt_required()
def editUser():
    try:
        userId = request.form.get('id')
        userId = userId if isinstance(userId, int) else int(userId)
        views = request.form.get('views')
        role_type = request.form.get('roleType')
        if role_type is not None:
            role_type = role_type if isinstance(role_type, int) else int(role_type)
        person_name = request.form.get('personName')
        password = request.form.get('password')
        if userId is None or not isinstance(userId, int):
            return {'code': 400, 'msg': "参数错误:userId"}
        if not isinstance(views, str):
            views = None
        if not isinstance(role_type, int):
            role_type = None
        if not isinstance(person_name, str):
            person_name = None
        if not isinstance(password, str) or len(password) > 16 or len(password) == 0:
            password = None
        flag, info = UserService.set_user_by_id(userId,
                                                {'views': views, 'roleType': role_type, 'personName': person_name,
                                                 'password': password})
        if not flag:
            return {'code': 400, 'msg': info}
        return {'code': 200, 'data': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/resetPassword', methods=['POST'])
@jwt_required()
def resetPassword():
    try:
        current_user_id = get_jwt_identity()
        current_user_id = current_user_id if isinstance(current_user_id, int) else int(current_user_id)
        oldPassword = request.form['oldPassword']
        newPassword = request.form['newPassword']
        flag, info = UserService.reset_password_by_id(current_user_id, oldPassword, newPassword)
        if not flag:
            return {'code': 400, 'msg': info}
        return {'code': 200, 'data': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/getAllView', methods=['POST'])
@jwt_required()
def getAllView():
    try:
        flag, info = PlatformViewServices.get_platform_views()
        if flag:
            data = [result.tran_to_dict() for result in info]
            return {'code': 200, 'data': data}
        else:
            return {'code': 400, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/getViewByIds', methods=['POST'])
@jwt_required()
def getViewByIds():
    viewIds = request.form.get('viewIds')
    if isinstance(viewIds, str):
        viewIds = tran_to_intArray(viewIds)
    if isinstance(viewIds, list):
        viewIds = [viewId if isinstance(viewIds, int) else int(viewId) for viewId in viewIds]
    vflag, views = PlatformViewServices.get_platform_view_by_ids(viewIds)
    if not vflag or len(views) == 0:
        return {'code': 200, 'data': []}
    return {'code': 200, 'data': [result.tran_to_dict() for result in views]}


@app.route('/addView', methods=['POST'])
@jwt_required()
def addView():
    try:
        viewname = request.form.get('name')
        parentid = request.form.get('parentId')
        parentid = parentid if isinstance(parentid, int) else int(parentid)
        viewurl = request.form.get('url')
        isMenu = request.form.get('type')
        isMenu = isMenu if isinstance(isMenu, int) else int(isMenu)
        orderKey = int(request.form.get('orderKey'))
        if not viewname or not isinstance(viewname, str):
            return {'code': 400, 'msg': '参数异常:viewName'}
        if not parentid or not isinstance(parentid, int):
            return {'code': 400, 'msg': '参数异常:parentId'}
        if not viewurl or not isinstance(viewurl, str):
            return {'code': 400, 'msg': '参数异常:viewUrl'}
        if not isMenu or not isinstance(isMenu, int):
            return {'code': 400, 'msg': '参数异常:isMenu'}
        if not orderKey or not isinstance(orderKey, int):
            return {'code': 400, 'msg': '参数异常:orderKey'}
        flag, info = PlatformViewServices.add_platform_view(viewname, viewurl, parentid, isMenu, orderKey)
        if not flag:
            return {'code': 400, 'msg': info}
        return {'code': 200, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/deleteView', methods=['POST'])
@jwt_required()
def deleteView():
    try:
        viewId = request.form.get('viewId')
        viewId = viewId if isinstance(viewId, int) else int(viewId)
        if not viewId or not isinstance(viewId, int):
            return {'code': 400, 'msg': '参数异常:viewId'}
        flag, info = PlatformViewServices.delete_platform_view_by_id(viewId)
        if not flag:
            return {'code': 400, 'msg': info}
        return {'code': 200, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/editView', methods=['POST'])
@jwt_required()
def updateView():
    try:
        viewId = request.form.get('id')
        viewId = viewId if isinstance(viewId, int) else int(viewId)
        viewname = request.form.get('name')
        parentid = request.form.get('parentId')
        parentid = parentid if isinstance(parentid, int) else int(parentid)
        viewurl = request.form.get('url')
        isMenu = request.form.get('type')
        isMenu = isMenu if isinstance(isMenu, int) else int(isMenu)
        orderKey = request.form.get('orderKey')
        orderKey = orderKey if isinstance(orderKey, int) else int(orderKey)
        if not viewId or not isinstance(viewId, int):
            return {'code': 400, 'msg': '参数异常:viewId'}
        if not viewname or not isinstance(viewname, str):
            return {'code': 400, 'msg': '参数异常:viewName'}
        if not parentid or not isinstance(parentid, int):
            return {'code': 400, 'msg': '参数异常:parentId'}
        if not viewurl or not isinstance(viewurl, str):
            return {'code': 400, 'msg': '参数异常:viewUrl'}
        if not isMenu or not isinstance(isMenu, int):
            return {'code': 400, 'msg': '参数异常:isMenu'}
        if not orderKey or not isinstance(orderKey, int):
            return {'code': 400, 'msg': '参数异常:orderKey'}
        platformView = PlatformView(
            id=viewId,
            view_name=viewname,
            parent_id=parentid,
            view_url=viewurl,
            is_menu=isMenu,
            order_key=orderKey
        )
        flag, info = PlatformViewServices.edit_platform_view(platformView)
        if flag:
            return {'code': 200, 'msg': info}
        else:
            return {'code': 400, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}


@app.route('/getAllShopName', methods=['POST'])
@jwt_required()
def getAllShopName():
    try:
        flag, info = CustomerInformationService.get_all_shop_list()
        if flag:
            return {'code': 200, 'msg': info}
        return {'code': 400, 'msg': info}
    except Exception as e:
        return {'code': 400, 'msg': str(e)}
